'use strict';

const Service = require('egg').Service;
class PublicService extends Service {
    async geta(table,url){
        const result = {}
        try {
            const uid = await this.app.mysql.get('table_http',{url:url});
            const re = await this.app.mysql.get(table,{http_id:uid.id})
            result.code = 200,
            result.message = '获取成功!'
            result.data_list = re
        } catch (error) {
            result.code = 201,
            result.message = error.message
        }
        return result
      }
  async geti(url){
    const result = {}
    
    try {
        const TABLE_NAME = 'table_http';
        const QUERY_STR = 'id, url';
        let sql = `select ${QUERY_STR} from ${TABLE_NAME} where url like "%${url}%"`;
        const uid = await this.app.mysql.query(sql)
        if(uid.length!=0){
            result.code = 200,
            result.message = '获取成功!' 
        }else{
            result.code = 202,
            result.message = '不存在域名信息!' 
        }
    } catch (error) {
        result.code = 201,
        result.message = error.message
    }

    return result
  }
  async getall(table,http_id){
    const result = {}
    try {
        const uid = await this.app.mysql.select(table,{http_id:http_id});
        if(uid){
            result.code = 200,
            result.message = '获取成功!'
            result.data_list = uid
        }else{
            result.code = 201,
            result.message = '获取失败，http_id不存在'
        }
    } catch (error) {
        result.code = 202,
        result.message = error.message
    }
    return result
  }
  async add(table,data){
    const result = {}
    try {
        const uid = await this.app.mysql.insert(table,data);
        if(uid.affectedRows===1){
            result.code = 200,
            result.message = '添加成功!'
            result.insertId = uid.insertId
        }else{
            result.code = 201,
            result.message = uid.message
        }

    } catch (error) {
        result.code = 202,
        result.message = error.message
    }
    return result
  }
  async update(table,data){
    const result = {}
    try {
        const uid = await this.app.mysql.update(table, data)
        if(uid.affectedRows===1){
            result.code = 200,
            result.message = '修改成功!'
        }else{
            result.code = 201,
            result.message = uid.message
        }

    } catch (error) {
        result.code = 202,
        result.message = error.message
    }
    return result
  }
  async delete(table,data){
    const result = {}
    try {
        const uid = await this.app.mysql.delete(table, {id:data.id})
        result.code = 200,
        result.message = '删除成功!'
    } catch (error) {
        result.code = 201,
        result.message = error.message
    }
    return result
  }
}

module.exports = PublicService;